package com.example.kotlintest.ui

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.example.kotlintest.viewmodel.DataViewModel
import com.example.kotlintest.R
import com.example.kotlintest.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private val viewModel: DataViewModel by viewModels()
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        val newsListAdapter = TouTiaoAdapter()
        val concatAdapter = newsListAdapter.withLoadStateFooter(
            FooterAdapter(newsListAdapter::retry)
        )
        binding.newsList.adapter = concatAdapter
        binding.swipeRefreshLayout.apply {
            setOnRefreshListener {
                newsListAdapter.refresh()
            }
        }
        lifecycleScope.launchWhenCreated {
            newsListAdapter.loadStateFlow.collectLatest {
                binding.swipeRefreshLayout.isRefreshing = it.refresh is LoadState.Loading
            }
        }
        lifecycleScope.launch {
            viewModel.toutiaoData().collectLatest {
                newsListAdapter.submitData(it)
            }
        }
    }
}